package com.qeeyou.apps.android.craftsman.activity.order;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RatingBar;
import android.widget.TextView;
import android.widget.Toast;

import com.qeeyou.apps.android.craftsman.R;
import com.qeeyou.apps.android.craftsman.activity.publish.ImagePreviewActivity;
import com.qeeyou.apps.android.craftsman.activity.publish.PublishStep2Activity;
import com.qeeyou.apps.android.craftsman.adapter.SelectImageGridAdapter;
import com.qeeyou.apps.android.craftsman.common.Contants;
import com.qeeyou.apps.android.craftsman.po.CommonInfo;
import com.qeeyou.apps.android.craftsman.po.MasterInfoByOrderId;
import com.qeeyou.apps.android.craftsman.po.OrderInfo;
import com.qeeyou.apps.android.craftsman.po.UploadImgInfo;
import com.qeeyou.apps.android.craftsman.service.APIConfig;
import com.qeeyou.apps.android.craftsman.service.AppService;
import com.qeeyou.apps.android.craftsman.utils.GifSizeFilter;
import com.qeeyou.apps.android.craftsman.utils.ImageLoader;
import com.qeeyou.apps.android.craftsman.view.CustomLoadingDialog;
import com.qeeyou.apps.android.craftsman.view.NoScrollGridView;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class ServiceEvaluateActivity extends Activity implements EasyPermissions.PermissionCallbacks {
    private static final String TAG = ServiceEvaluateActivity.class.getSimpleName();

    private static final int RC_CAMERA_PERM = 123;

    private Context mContext;

    private ImageView btnBack;
    private ImageView ivMasterAvatar;
    private TextView tvMasterName;
    private RatingBar rbMasterScore;
    private TextView tvMasterOrderCount;
    private TextView tvMasterAge;
    private TextView tvMasterAddress;
    private RatingBar rbCommentStar;
    private EditText etCommentContent;
    private NoScrollGridView nsgvCommentImage;
    private CheckBox cbCommentIsAnonymous;
    private Button btnCommentSubmit;

    private SelectImageGridAdapter mGridAdapter;
    private List<String> mImagePathList = new ArrayList<String>();

    private CustomLoadingDialog mLoadingDialog;

    private OrderInfo mOrderInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_evaluate);

        mContext = this;

        mOrderInfo = (OrderInfo) getIntent().getSerializableExtra("orderInfo");

        setView();

        setEvent();
    }

    private void setView() {
        btnBack = (ImageView) this.findViewById(R.id.btnBack4ServiceEvaluate);
        ivMasterAvatar = (ImageView) this.findViewById(R.id.ivMasterAvatar4ServiceEvaluate);
        tvMasterName = (TextView) this.findViewById(R.id.tvMasterName4ServiceEvaluate);
        rbMasterScore = (RatingBar) this.findViewById(R.id.rbMasterScore4ServiceEvaluate);
        tvMasterOrderCount = (TextView) this.findViewById(R.id.tvMasterOrderCount4ServiceEvaluate);
        tvMasterAge = (TextView) this.findViewById(R.id.tvMasterAge4ServiceEvaluate);
        tvMasterAddress = (TextView) this.findViewById(R.id.tvMasterAddress4ServiceEvaluate);
        rbCommentStar = (RatingBar) this.findViewById(R.id.rbCommentStar4ServiceEvaluate);
        etCommentContent = (EditText) this.findViewById(R.id.etCommentContent4ServiceEvaluate);
        nsgvCommentImage = (NoScrollGridView) this.findViewById(R.id.nsgvCommentImage4ServiceEvaluate);
        cbCommentIsAnonymous = (CheckBox) this.findViewById(R.id.cbCommentIsAnonymous4ServiceEvaluate);
        btnCommentSubmit = (Button) this.findViewById(R.id.btnCommentSubmit4ServiceEvaluate);

        mGridAdapter = new SelectImageGridAdapter(this, mImagePathList, 4);
        nsgvCommentImage.setAdapter(mGridAdapter);

        if (mOrderInfo != null) {
            String params[] = {mOrderInfo.getOrderid()};
            new GetMasterInfoByOrderidAction().execute(params);
        }
    }

    private void setEvent() {
        btnBack.setOnClickListener(onBackClickListener);

        mGridAdapter.setOnItemClickListener(new SelectImageGridAdapter.OnItemClickListener() {
            @Override
            public void onItemImageClick(int position) {
                if (position == mImagePathList.size()) {
                    cameraTask();
                } else {
                    startActivityForResult(new Intent(mContext, ImagePreviewActivity.class)
                                    .putExtra(Contants.Extra.EXTRA_IMAGE_ID, position)
                                    .putExtra(Contants.Extra.EXTRA_IMAGE_LIST, (Serializable) mImagePathList)
                                    .putExtra(Contants.Extra.EXTRA_IMAGE_PREVIEW_IS_SHOW_DELETE, true)
                            , Contants.RequestCode.REQUEST_IMAGE_PREVIEW);
                }
            }

            @Override
            public void onItemCancelClick(int position) {
                mImagePathList.remove(position);
                mGridAdapter.update(mImagePathList);
            }
        });

        btnCommentSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mImagePathList.size() > 0) {
                    new UploadImageAction().execute();
                } else {
                    String serquality = String.valueOf((int)rbCommentStar.getRating());
                    String memo = etCommentContent.getText().toString();
                    String commentimg = "";
                    String isanonymous = cbCommentIsAnonymous.isChecked() ? "0" : "1";
                    String params[] = {mOrderInfo.getOrderid(), serquality, memo, commentimg, isanonymous};
                    new CommentOrderAction().execute(params);
                }
            }
        });
    }

    private View.OnClickListener onBackClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            finish();
        }
    };

    @AfterPermissionGranted(RC_CAMERA_PERM)
    public void cameraTask() {
        if (EasyPermissions.hasPermissions(this,
                new String[]{Manifest.permission.CAMERA,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE
                })) {
            // Have permission, do the thing!
            Matisse.from((Activity) mContext)
                    .choose(MimeType.ofAll(), false)
                    .countable(true)
                    .capture(true)
                    .captureStrategy(new CaptureStrategy(true, Contants.Client.FILE_PROVIDER))
                    .maxSelectable(4 - mImagePathList.size())
                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
                    .gridExpectedSize(
                            getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                    .thumbnailScale(0.85f)
                    .imageEngine(new GlideEngine())
                    .forResult(Contants.RequestCode.REQUEST_TAKE_IMAGE_FROM_ALBUM);
        } else {
            // Ask for one permission
            EasyPermissions.requestPermissions(
                    this,
                    getString(R.string.permission_request_denied),
                    RC_CAMERA_PERM,
                    new String[]{
                            Manifest.permission.CAMERA,
                            Manifest.permission.WRITE_EXTERNAL_STORAGE});
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           @NonNull String[] permissions,
                                           @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        // EasyPermissions handles the request result.
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsGranted:" + requestCode + ":" + perms.size());
    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        Log.d(TAG, "onPermissionsDenied:" + requestCode + ":" + perms.size());

        // (Optional) Check whether the user denied any permissions and checked "NEVER ASK AGAIN."
        // This will display a dialog directing them to enable the permission in app settings.
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case Contants.RequestCode.REQUEST_TAKE_IMAGE_FROM_ALBUM:
                if (resultCode == RESULT_OK) {
                    mImagePathList.addAll(Matisse.obtainPathResult(data));
                    mGridAdapter.update(mImagePathList);
                }
                break;
            case Contants.RequestCode.REQUEST_IMAGE_PREVIEW:
                if (resultCode == RESULT_OK) {
                    mImagePathList = (List<String>) data.getSerializableExtra(Contants.Extra.EXTRA_IMAGE_LIST);
                    mGridAdapter.update(mImagePathList);
                }
                break;
        }
    }

    class GetMasterInfoByOrderidAction extends AsyncTask<String, Void, MasterInfoByOrderId> {
        public GetMasterInfoByOrderidAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(mContext);
            }
            mLoadingDialog.setMessage("正在获取师傅信息...");
            mLoadingDialog.show();
        }

        @Override
        protected MasterInfoByOrderId doInBackground(String... params) {
            String orderid = params[0];//订单id(从订单列表获取)
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("orderid", orderid);
            MasterInfoByOrderId masterInfo = AppService.getInstance().getMasterInfoByOrderid(paramMap);
            return masterInfo;
        }

        @Override
        protected void onPostExecute(MasterInfoByOrderId masterInfo) {
            super.onPostExecute(masterInfo);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (masterInfo != null) {
                ImageLoader.getInstance()
                        .displayListHeaderPic(mContext, APIConfig.BASE_URL + masterInfo.getAvatar(), ivMasterAvatar);
                tvMasterName.setText(masterInfo.getMastername());
                rbMasterScore.setRating(Integer.valueOf(masterInfo.getScore()));
                tvMasterOrderCount.setText("安装: " + masterInfo.getOrdercount() + "次");
                tvMasterAge.setText("年龄: " + masterInfo.getAge() + "岁");
                tvMasterAddress.setText(masterInfo.getAddress());
            }
        }
    }

    class UploadImageAction extends AsyncTask<String, Void, List<String>> {
        public UploadImageAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(mContext);
            }
            mLoadingDialog.setMessage("正在上传图片...");
            mLoadingDialog.show();
        }

        @Override
        protected List<String> doInBackground(String... params) {
            List<String> uploadImgInfos = AppService.getInstance().uploadImages(mImagePathList);
            return uploadImgInfos;
        }

        @Override
        protected void onPostExecute(List<String> uploadImgInfos) {
            super.onPostExecute(uploadImgInfos);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (uploadImgInfos != null) {
                String serquality = String.valueOf((int)rbCommentStar.getRating());
                String memo = etCommentContent.getText().toString();
                String commentimg = "";
                for (String imgInfo : uploadImgInfos) {
                    commentimg += imgInfo + ",";
                }
                if (commentimg.length() > 0) {
                    commentimg = commentimg.substring(0, commentimg.length() - 1);
                }
                String isanonymous = cbCommentIsAnonymous.isChecked() ? "0" : "1";
                String params[] = {mOrderInfo.getOrderid(), serquality, memo, commentimg, isanonymous};
                new CommentOrderAction().execute(params);
            }
        }
    }

    //对订单进行评价
    class CommentOrderAction extends AsyncTask<String, Void, CommonInfo> {
        public CommentOrderAction() {
            super();
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            if (mLoadingDialog == null) {
                mLoadingDialog = new CustomLoadingDialog(mContext);
            }
            mLoadingDialog.setMessage("正在提交评价...");
            mLoadingDialog.show();
        }

        @Override
        protected CommonInfo doInBackground(String... params) {
            String orderid = params[0];//订单id(从订单列表获取)
            String serquality = params[1];//评分星级
            String memo = params[2];//评价备注
            String commentimg = params[3];//图片地址(由,分隔)
            String isanonymous = params[4];//是否匿名(0:不匿名[默认];1:匿名)
            Map<String, String> paramMap = new HashMap<String, String>();
            paramMap.put("orderid", orderid);
            paramMap.put("serquality", serquality);
            paramMap.put("memo", memo);
            paramMap.put("commentimg", commentimg);
            paramMap.put("isanonymous", isanonymous);
            CommonInfo resultInfo = AppService.getInstance().commentOrder(paramMap);
            return resultInfo;
        }

        @Override
        protected void onPostExecute(CommonInfo resultInfo) {
            super.onPostExecute(resultInfo);
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            if (resultInfo != null && resultInfo.getStatus().equalsIgnoreCase("1")) {
                Toast.makeText(mContext, "评价提交成功", Toast.LENGTH_SHORT).show();
                setResult(RESULT_OK);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        finish();
                    }
                }, 1000);
            } else {
                Toast.makeText(mContext, "评价提交失败", Toast.LENGTH_SHORT).show();
            }
        }
    }
}
